package com.czk.linkedList.sinaInterview;


import lombok.Data;
import lombok.ToString;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/6/14 13:28
 */
public class SinaInterviewTest {
    public static void main(String[] args) {
        SinaInterview sinaInterview=new SinaInterview();
        Node node3 = new Node(3);
        Node node2 = new Node(2);
        Node node1 = new Node(1);
        sinaInterview.addNode(node1);
        sinaInterview.addNode(node2);
        sinaInterview.addNode(node3);
        System.out.println(sinaInterview.getLinkedListLength());
        System.out.println(sinaInterview.findLastIndexNode(3));
    }
}

class SinaInterview {
    Node node=new Node(1);
    // 增加链表元素
    public void addNode(Node node){
        Node temp=this.node;
       while (true){
           if (temp.next==null){
               temp.setNext(node);
               break;
           }
           temp=temp.next;
       }
    }


    // 链表有效节点个数
    public int getLinkedListLength() {
        // 判断节点是否为空
        if(this.node.next==null) return 0;
        // 变量接受
        Node current=this.node.next;
        int i=0;
        // 判断下一结点是否为空
        while (current!=null){
            i++;
            current=current.next;
        }
        return i;
    }
    // 倒数第n个节点
    public Node findLastIndexNode(int n){
        if (node.next==null) return null;
        // 得到的链表的长度
        int size=this.getLinkedListLength();
        // 第二次遍历 size-n+1就是倒数的节点
        if(size<n || n<0) return null;
            int i=0;
            Node current=this.node;
            while (i!=size-n+1){
                current=current.next;
                i++;
            }
            return current;
    }
}
@Data
@ToString
class Node{
    public Object data;
    public Node next;

    public Node(Object data) {
        this.data = data;
    }
}
